package com.example.system.controller;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.commons.core.domain.BaseResponse;
import com.example.commons.core.entity.SystemDepartment;
import com.example.system.service.ISystemDepartmentService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门前端控制器
 */
@RestController
@RequestMapping("sys/dept")
public class SystemDepartmentController {

    private final ISystemDepartmentService systemDepartmentService;

    public SystemDepartmentController(ISystemDepartmentService systemDepartmentService) {
        this.systemDepartmentService = systemDepartmentService;
    }

    @RequestMapping("/deptList")
    public BaseResponse<List<Tree<String>>> deptList(){
        List<Tree<String>> deptTreeList = systemDepartmentService.getDeptList();
        return BaseResponse.ok(deptTreeList);
    }

    @PostMapping("/addDept")
    public BaseResponse<Void> addDept(@RequestBody SystemDepartment systemDepartment){
        if(systemDepartment.getParentId() == null){
            systemDepartment.setParentId(0L);
        }
        systemDepartmentService.save(systemDepartment);
        return BaseResponse.ok();
    }

    @PostMapping("/deleteDept/{deptId}")
    public BaseResponse<Void> deleteDept(@PathVariable("deptId") Long deptId){
        // 删除部门
        systemDepartmentService.removeById(deptId);
        // 删除部门下的所有子部门
        systemDepartmentService.remove(new LambdaQueryWrapper<SystemDepartment>().eq(SystemDepartment::getParentId, deptId));
        return BaseResponse.ok();
    }

}
